/**
 * http配置
 */

import axios, { AxiosRequestConfig } from 'axios';
import { downloadFile } from '@/common/util';
import store from '@/store'
import { Toast } from 'vant';
import router from '../router';

function buildHeader(): { [key: string]: string } {
    return {
        'Content-Type': 'application/json;charset=UTF-8;multipart/form-data'
    };
}

export const ax = axios.create({
    baseURL: host(),
    headers: buildHeader(),
    timeout: 300000,
    responseType: 'json',
    withCredentials: false,
    transformRequest: [
        function (data) {
            if (data instanceof FormData) return data;
            return JSON.stringify(data);
        }
    ],
    transformResponse: [
        function (data) {
            if (data) {
                var data = typeof data == 'object' ? data : JSON.parse(data); //兼容IE
                return data;
            } else {
                const msg = 'Unknow Error';
                throw new Error(msg);
            }
        }
    ],
    // `onUploadProgress`允许处理上传的进度事件
    onUploadProgress: function (progressEvent) {
        // 使用本地 progress 事件做任何你想要做的
    },
    // `onDownloadProgress`允许处理下载的进度事件
    onDownloadProgress: function (progressEvent) {
        // Do whatever you want with the native progress event
    }
});

export function host(): string {
    if (window.location.hostname == 'localhost' || window.location.hostname.indexOf('192.168') > -1) {
        return '/'; //代理
        // return 'http://192.168.3.217:5000/'; //胡庆伟
    } else {
        return '/';
    }
}

// http request 拦截器
ax.interceptors.request.use(
    config => {
        let userinfo = JSON.parse(localStorage.getItem('userinfo') as string);
        if (userinfo) {
            config.headers.UserId = `${userinfo.id}`;
            config.headers.UserToken = `${userinfo.password}`;
        }
        return config;
    },
    err => {
        // return Promise.reject(err);
    }
);

// http response 拦截器
ax.interceptors.response.use(
    (response): any => {
        if (!response.data.success) {
            switch (response.data.errorCode) {
                case '1001': //未登录
                    router.push('/login');
                    localStorage.clear();
                    Toast(response.data.errorMessage);
                    break;
                default:
                    Toast(response.data.errorMessage);
                    return Promise.reject(response.data.errorMessage);
            }

        } else {
            return Promise.resolve(response.data);
        }
    },
    error => {
        if (error.code === 'ECONNABORTED') {
            Toast('接口超时！');
        }
        if (error.response) {
            switch (error.response.status) {
                case 502:
                    Toast('后台发布中，请稍候！');
                    break;
            }
        }
    }
);
/* GET  */
export function Get<T>(url: string, data: T): Promise<any> {
    // `params`是要与请求一起发送的URL参数
    // 必须是纯对象或URLSearchParams对象
    return ax
        .get(url, {
            params: data
        })
        .then(res => {
            return res.data;
        })
        .catch(err => {
            throw err;
        });
}

//下载excel
export function Download<T>(url: string, data: T): Promise<any> {
    return axios({
        baseURL: host(),
        url: url,
        params: data,
        headers: { Authorization: `Bearer ${store.state.jwtToken}` },
        method: 'get',
        responseType: 'arraybuffer' //二进制流
    })
        .then(res => {
            ab2str(res.data, function (str: string) {
                try {
                    const obj = JSON.parse(str);
                    if (typeof obj == 'object' && obj) {
                        if (obj.errorMessage) {
                            Toast(obj.errorMessage);
                            return;
                        }
                    } else {
                        downloadFile(res);
                    }
                } catch (e) {
                    downloadFile(res);
                }
            });
        })
        .catch(err => {
            Toast('导出失败');
        });
    function ab2str(u: BlobPart, f: { (str: any): void; call?: any; }) {
        const b = new Blob([u]);
        const r = new FileReader();
        r.readAsText(b, 'utf-8');
        r.onload = function () { if (f) f.call(null, r.result) }
    }
}

//上传流文件
export function Import<T>(url: string, data: T): Promise<any> {
    return ax
        .post(url, data, {
            method: 'post',
            headers: { 'Content-Type': 'multipart/form-data' }
        })
        .then(res => {
            return res.data;
        })
        .catch(err => {
            throw err;
        });
}

/* POST */
export function Post<T>(url: string, data: T): Promise<any> {
    return ax
        .post(url, data)
        .then(res => {
            return res.data;
        })
        .catch(err => {
            throw err;
        });
}
/* PUT */
export function Put<T>(url: string, data: T): Promise<any> {
    return ax
        .put(url, data)
        .then(res => {
            return res.data;
        })
        .catch(err => {
            throw err;
        });
}
/* PATCH */
export function Patch<T>(url: string, data: T): Promise<any> {
    return ax
        .patch(url, data)
        .then(res => {
            return res.data;
        })
        .catch(err => {
            throw err;
        });
}
/* DELETE */
export function Delete<T>(url: string, data: T): Promise<any> {
    return ax
        .delete(url, data)
        .then(res => {
            return res.data;
        })
        .catch(err => {
            throw err;
        });
}
